'use server';
import { formatFindParams } from '@/pao/server/serverPrisma';
import { PrismaClient, KnowledgePoint } from '@/data/prisma';

const prisma = new PrismaClient()

export async function query(filter: Record<string, any>
	, sorter: Record<string, any>
	, pageSize: number = 50
	, pageIndex: number = 1
	, columnFilterTypes: Record<string, string> = {}): Promise<{ rows: KnowledgePoint[]; total: number; }> {
	const subjects = await prisma.knowledgePoint.findMany(formatFindParams(filter, sorter, pageSize, pageIndex, columnFilterTypes))
	return { rows: subjects as unknown as KnowledgePoint[], total: subjects.length }
}

export async function deleteRow(row: KnowledgePoint) {
	await prisma.knowledgePoint.delete({ where: { id: row.id } })
}

export async function editRow(row: KnowledgePoint) {
	await prisma.knowledgePoint.update({ where: { id: row.id }, data: row })
}

export async function addRow(row: KnowledgePoint) {
	await prisma.knowledgePoint.create({ data: row })
}


export async function modifyRows(rows: KnowledgePoint[], originRows: KnowledgePoint[]) {
	await prisma.knowledgePoint.updateMany({
		data: rows.filter(row => originRows.find(originRow => originRow.id === row.id) !== undefined).map(row => ({ where: { id: row.id }, data: row }))
	})
	await prisma.knowledgePoint.createMany({
		data: rows.filter(row => originRows.find(originRow => originRow.id === row.id) === undefined)
	})
	originRows.filter(originRow => rows.find(row => originRow.id === row.id) !== undefined).forEach(async row => {
		await prisma.knowledgePoint.delete({ where: { id: row.id } })
	});
}
